﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using System.Threading;
using PwdMgrUI.Objects;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using PwdMgr.PwdMgrService;
using PwdMgr.CommonContract;
using PwdMgrUI.Utils;

namespace PwdMgrUI
{
    /// <summary>
    /// Interaction logic for Search.xaml
    /// </summary>
    public partial class Search : UserControl
    {
        public Search()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(Search_Loaded);
        }

        private SearchThread _searchThread;

        void Search_Loaded(object sender, RoutedEventArgs e)
        {
            Init();
        }

        private void Init()
        {
            this.tbox_SearchText.TextChanged += new TextChangedEventHandler(Tbox_SearchText_TextChanged);
        }
        
        void Tbox_SearchText_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox tboxTmp = (TextBox)sender;

            if (_searchThread == null)
            {
                _searchThread = new SearchThread();
                _searchThread.SearchStarted += new Action(SearchThread_SearchStarted);
                _searchThread.SearchCompleted += new Action<object>(SearchThread_SearchCompleted);
            }

            _searchThread.QuickSearch(tboxTmp.Text);
        }

        void SearchThread_SearchCompleted(object obj)
        {
            UIInvoke(new Action(() =>
            {
                this.dg_Content.ItemsSource = obj as IEnumerable;
                this.tblk_Loading.Visibility = System.Windows.Visibility.Hidden;
            }));
        }

        void SearchThread_SearchStarted()
        {
            UIInvoke(new Action(() =>
            {
                this.tblk_Loading.Visibility = System.Windows.Visibility.Visible;
            }));
        }

        private void UIInvoke(Action action)
        {
            if (CheckAccess())
            {
                action();
            }
            else
            {
                Dispatcher.Invoke(action);
            }
        }

        private void Tblk_RowPassword_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            UIAlert.Error("aaa");
        }
    }
}
